"use strict";

const Controller = require("egg").Controller;

// 定义校验数据规则
const vUser = {
  username: {
    type: "string",
    required: true,
  },
  password: {
    type: "string",
    required: true,
  },
};

const vList = {
  pagesize: 'number',
  pagenum: 'number'
}

const vEditUser = {
  user_id: 'string',
  username: {type: 'string', required: true, min: 3, max: 15},
  phone: {type: 'string', required: false, min: 11, max: 11},
  realname: 'string?',
  email: 'email?',
  sex: [1, 2, '1', '2']
}

class UsersController extends Controller {
  // 注册用户
  async register() {
    const { ctx, service } = this;
    const params = ctx.request.body;
    ctx.validate(vUser, params);
    const isExist = await service.users.user.checkUser(params);
    if (isExist) {
      ctx.body = ctx.fail("用户名已存在");
    } else {
      const res = await service.users.user.registerUser(params);
      if (res.affectedRows === 1) {
        ctx.body = ctx.success("注册成功", null);
      } else {
        ctx.body = ctx.fail("注册失败");
      }
    }
  }
  // 登陆
  async login() {
    const { ctx, service, app } = this;
    const params = ctx.request.body;
    ctx.validate(vUser, params);
    const res = await service.users.user.login(params);
    if (res.data) {
      // 生成token
      const token = app.jwt.sign({
          user_id: res.data.user_id,
          username: params.username,
          password: params.password
      }, app.config.jwt.secret)
      const userinfo = {...res.data}
      delete userinfo.password
      ctx.body = ctx.success(res.msg, {
        userinfo,
        token
      });
    }else {
      ctx.body = ctx.fail(res.msg)
    }
  }
  // 获取用户信息
  async getUserInfo(){
    const { ctx, service, app } = this;
    const res = await service.users.user.getUserInfo()
    if(res[0]){
      ctx.body = ctx.success('获取用户信息成功', res[0])
    }else {
      ctx.body = ctx.fail('获取用户信息失败')
    }
  }
  // 获取用户列表
  async getUserList(){
    const { ctx, service } = this
    ctx.validate(vList, ctx.request.body)
    const res = await service.users.user.getUserList(ctx.request.body)
    ctx.body = ctx.list('获取用户列表成功', {
      data: res.data,
      total: res.total
    })
  }
  // 编辑用户
  async editUser(){
    const { ctx, service } = this
    ctx.validate(vEditUser, ctx.request.body)

    const res = await service.users.user.editUser(ctx.request.body)
    if(res.affectedRows === 1){
      ctx.body = ctx.success('修改用户成功')
    }else {
      ctx.body = ctx.fail('修改用户失败')
    }
  }
  // 删除用户
  async deleteUser(){
    const { ctx, service } = this
    const res = await service.users.user.deleteUser(ctx.params)
    if(res.affectedRows === 1){
      ctx.body = ctx.success('删除用户成功')
    }else {
      ctx.body = ctx.fail('删除用户失败')
    }
  }
}

module.exports = UsersController;
